package com.peaksport.pkms.edge.handler;

import java.util.concurrent.CompletableFuture;

import org.apache.servicecomb.core.Handler;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.provider.pojo.Invoker;
import org.apache.servicecomb.swagger.invocation.AsyncResponse;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;

import com.peaksport.framework.util.PKContextUtils;
import com.peaksport.framework.util.PKPublicUtils;
import com.peaksport.framework.vo.JSONResultSet;
import com.peaksport.pkms.edge.interfaces.PKOAuth;
import com.peaksport.pkms.oauth.vo.TokenVO;

public class PKOAuthHandler implements Handler {

	private static final String Service_permit = "pkms-permit";
	private static PKOAuth pkOAuth;
	static {
		pkOAuth = Invoker.createProxy(Service_permit, "pkms-permit-pkOAuth", PKOAuth.class);
	}
	@Override
	public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
		if (!needVaildToken(invocation)) {
			invocation.next(asyncResp);
			return;
		}
		HttpServletRequestEx requestEx =  invocation.getRequestEx();
		String pathInfo = requestEx.getPathInfo();
		String token = requestEx.getParameter("token");
		if (PKPublicUtils.isEmpty(token)) token = requestEx.getHeader("token");
		if (PKPublicUtils.isEmpty(token)) {
			JSONResultSet rs = JSONResultSet.create();
			rs.setResultMsg("请传入token信息.");
			rs.setResultCode(98);
			StringBuffer detailExpMsg = new StringBuffer(); 
			detailExpMsg.append("url: ").append(pathInfo);
			rs.setDetailExpMsg(detailExpMsg.toString());
			asyncResp.consumerFail(new InvocationException(403, "", rs));
			return;
		}
		//校验token有效性&接口权限
		CompletableFuture<TokenVO> future = pkOAuth.vaildOAuth(token,pathInfo);
		String token1 = token;
		future.whenComplete((result,exc) -> {
			if (exc != null) {
				asyncResp.consumerFail(exc);
				return;
			}
			
			try {
				CompletableFuture<String> futureSession = pkOAuth.getContextByToken(token1);
				futureSession.whenComplete((sessionId,exc1) -> {
					if (exc1 != null) {
						asyncResp.consumerFail(exc1);
						return;
					}
					try {
						invocation.getContext().put(PKContextUtils.session_context_key, sessionId);
						invocation.next(asyncResp);
					} catch(Exception e) {
						asyncResp.consumerFail(e);
					}
				});

			} catch (Exception e) {
				asyncResp.consumerFail(e);
			}
			
		});
	}
	/**
	 * 是否需要校验token信息
	 * @param invocation
	 * @return
	 */
	private boolean needVaildToken(Invocation invocation) {
		String serviceName = invocation.getMicroserviceName();
		String schemaId = invocation.getSchemaId();
		String path = invocation.getOperationName();
		boolean b1 = "pkms-permit".equals(serviceName) && "pkms-permit-pkOAuth".equals(schemaId);
		boolean b2 = "pkms-permit".equals(serviceName) && "pkms-permit-sso".equals(schemaId) && "login".equals(path);
		boolean b3 = "pkms-permit".equals(serviceName) && "pkms-permit-sso".equals(schemaId) && "logout".equals(path);
		return !b1 && !b2 && !b3;
	}
	
}
